#! /usr/bin/python
# -*- coding: latin-1 -*-

from urllib2 import Request, urlopen, URLError
import glob
import urllib2
import urllib
import os
import sys
from os.path import exists




def openURL(url):
        """ 
        Open an url and check erros
        
        Args:
           url: the url to open
        Returns:
           returns a file-like object with two additional methods:
                   geturl()   return the URL of the resource retrieved, commonly used to determine if a redirect was followed
                   info()   return the meta-information of the page, such as headers, in the form of an mimetools.Message instance (see Quick Reference to HTTP Headers)
                   getcode()   return the HTTP status code of the response.

        Raises:
        """
        req = urllib2.Request(url)
        try:
                handle = urllib2.urlopen(req)
        except IOError,e:
                if hasattr(e, 'reason'):
                        print 'We failed to reach a server.'
                        print 'Reason: ', e.reason
                elif hasattr(e, 'code'):
                        print 'The server couldn\'t fulfill the request.'
                        print 'Error code: ', e.code
                else :
                        print 'ok'
        else:
                print 'cest bon'
                return  handle.read()


########################################################################################################################################################

def getMovieHtmlPage(path):
        """ 

        Get a allocine movie page
        
        Args:
             path: path of the movie file

        returns a file-like object with two additional methods:
                   geturl()   return the URL of the resource retrieved, commonly used to determine if a redirect was followed
                   info()   return the meta-information of the page, such as headers, in the form of an mimetools.Message instance (see Quick Reference to HTTP Headers)
                   getcode()   return the HTTP status code of the response.
        """

        name = path.replace(dir,"").split(os.sep)[1]
        ext = name.split('.')[-1]
        
        titre = name.replace("."+ext,"").replace("[","(").replace("]","(").replace("."," ").split('(')[0].replace(" ","+").replace("\\","").lower()

	the_url = "http://www.allocine.fr/recherche/?q={0}".format(titre)
                
        return         openURL(the_url) 


########################################################################################################################################################

def search(path,directory,i,taille):
        """ 
        Main function
        
        Args:
           path: path of the file
           directory: folder with the movies
        Returns:
           nothing
        Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

	 Fonction principale. Parametres : chemin du fichier,  dossier de travail, iteration 	 nombre de films.
        """

        result =  getMovieHtmlPage(path)      
        if "<a href='/film/fichefilm_gen_cfilm" in result:
                id = result.split("<a href='/film/fichefilm_gen_cfilm=")[1].split(".html")[0]
                lien = "http://www.allocine.fr/film/fichefilm_gen_cfilm={0}.html".format(id)
                print lien        
                result =         openURL(lien) 
                if '<span itemprop="director"' in result:
                        auteur=result.split('<span itemprop="director" itemscope itemtype="http://schema.org/Person"><a title="')[1]\
                                     .split('" href="/personne')[0]
                        print auteur
                        if '<span itemprop="genre">' in result:
                                genre = result.split('<span itemprop="genre">')[1].split('</span>')[0]
                                print genre
                                #print "({0} / {1}) Ajoute a la liste {2})".format(i+1,taille,path+" ("+genre+")")
                                #ordonner(directory,path,genre,name)
                        if '<span itemprop="director"' in result:
                                auteur=result.split('<span itemprop="director" itemscope itemtype="http://schema.org/Person"><a title="')[1]\
                                     .split('" href="/personne')[0]
                                
                                print auteur
                        if '<span itemprop="duration"' in result:
                                duree = result.split('<span itemprop="duration"')[1].split('</span>')[0].split('>')[1]
                                print duree
                                                        
                        if '<strong><span itemprop="datePublished"' in result:
                                date=result.split('<strong><span itemprop="datePublished"')[1]\
                                           .split('</span>')[0].split('>')[1]
                                print date

                        if '<span class="note">' in result:
                                presse=result.split('<span class="note">')[1]\
                                             .split('</span>')[0].split('>')[1]
                                print presse
                                
                        if '<p itemprop="description">' in result:
                                synopsis=result.split('<p itemprop="description">')[1]\
                                               .split('</p>')[0]
                                print synopsis



# def ordonner(directory,path,genre,name):
#         """ En parametres : dossier de travail, chemin du fichier, genre du film, nom du film.
# 	Effectue le tri en fonction du genre du film """

# 	if not exists(directory+os.sep+genre):
#                 os.mkdir(directory+os.sep+genre, 0775)

# 	#os.rename(path,\
#                 #directory+os.sep+genre+os.sep+name)

# 	print "Fichier deplace avec succes"


if __name__ == "__main__":
        if len(sys.argv) >2:
                print("Precisez un dossier de travail en parametre, avec des fichiers en de films")
                sys.exit(1)
        else:
                dir = sys.argv[1]
                liste = glob.glob(dir+os.sep+"*.avi")+glob.glob(dir+os.sep+"*.divx")+glob.glob(dir+os.sep+"*.mkv")
                print '\n'.join(liste)
                taille = len(liste)
                i = 0

   	print "Il y a {0} films a traiter dans le dossier {1}. Voulez-vous proceder au rangement de vos films par Genre d'apres Allocine ? (O/N)".format(taille,dir)
        continuer = raw_input()
        if continuer=="o" or continuer=="O":
                for file in liste:
                        search(file,dir,i,taille)
                        i=i+1

		print "Done !"
        else:
                print "Comme tu veux ..."
